// pages/apNetwork/apNetwork.js
var util = require('../../utils/util.js');
var CryptoJS=require('../../utils/aes.js');
const log = require('../../utils/log.js');
const app = getApp();
var udp;
var udpDiscover;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    curWifi:'wifi名称',
    inputNewPwdValue:'',
    apWifi:[],
    port:0,
    apGuangBo:'',
    wifiGuangBo:'',
    iswifiGuangBo:true,
    scanQRmodelID:'',//modelID即6位产品型号
    iswifiList:'', //计时器循环获取wifi列表
    isConnecting:false,
    isMatch:false, //是否匹配
    progressVal: 0, //进度条值
    progressInter:''//进度条定时器
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      scanQRmodelID: options.qRCodeMsg
    })
    console.log(this.data.scanQRmodelID)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 初始化 Wi-Fi 模块。
    var that=this;
    if (!app.globalData.isAndroidPlatform) {
      wx.showModal({
        title: '提示',
        content: '由于系统限制，iOS用户请手动进入系统WiFi页面，然后返回小程序。',
        showCancel: false,
        success() {
          that.startWifi()
        }
      })
      return
    }
    that.startWifi();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.progressInter);
    clearInterval(this.data.wifiGuangBo);
    clearInterval(this.data.apGuangBo);
    wx.stopWifi({
      success(res) {
        console.log(res.errMsg);
        // 关闭 Wi-Fi 模块。
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取输入密码
  bindNewPwdInput: function (e) {
    this.setData({
      inputNewPwdValue: e.detail.value
    })
  },
  // 初始化wifi
  startWifi() {
    var that = this;
    // 连接wifi
    wx.startWifi({
      success(res) {
        console.log(res.errMsg);
        // 获取已连接中的 Wi-Fi 信息。
        wx.getConnectedWifi({
          success(res) {
            console.log(res);
            that.setData({
              curWifi: res.wifi.SSID
            })
          },
          fail(err) {
            console.log(err);
          }
        })
      }
    })
  },
  // 连接热点发送完广播并收到回复后，开始连接路由器并发生设备发现
  sendDiscoverFun() {
    var that = this;
    udpDiscover = wx.createUDPSocket();
    var locationPort = udpDiscover.bind();
    console.log("当前端口 " + locationPort);
    clearInterval(that.data.wifiGuangBo);
    that.setData({
      isMatch:false
    })
    var times;
    that.data.wifiGuangBo = setInterval(function () {
      times = Date.parse(new Date()) / 1000;
      var parm = {
        "modelId": that.data.scanQRmodelID,
        "platform": "0",
        "timestmp": times.toString()
      }
      udpDiscover.send({
        address: '255.255.255.255',
        port: 7686,
        message: JSON.stringify(parm)
      })
      console.log("send: " + JSON.stringify(parm))
    }, 1000)
    udpDiscover.onMessage(function (res) {
      clearInterval(that.data.wifiGuangBo);
      var mes = util.newAb2Str(res.message);
      console.log("recv: " + mes);
      var jsonMes = JSON.parse(mes);
      var decDid = jsonMes.deviceId;
      var keyVar = jsonMes.key;
      var bit = keyVar.substring((keyVar.length)-16);
      var timestamp = new Date().getTime();
      udpDiscover.close();
      var param = {
        "model": jsonMes.modelId,
        'pin': jsonMes.key,
        'timestamp': times
      }
      var params = JSON.stringify(param);
      wx.request({
        url: 'https://papi.zcyun.cn/v1/user/device/bind/' + jsonMes.deviceId,
        method: "POST",
        data: {
          "model": jsonMes.modelId,
          'pin': jsonMes.key,
          'timestamp': times
        },
        header: {
          'content-type': 'application/json', // 默认值
          'openId': app.globalData.openId,
          'ts': timestamp,
          'sign': util.sha1("POST" + '/v1/user/device/bind/' + jsonMes.deviceId + params + timestamp + app.globalData.openKey)
        },
        success(res) {
          console.log(JSON.stringify(res.data));
          if (res.data.code == 0) {
            wx.showToast({
              title: '成功添加设备',
              icon: 'none'
            })
            // 返回设备列表
            wx.switchTab({
              url: '../index/index'
            })
          }else{
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    })
  },
  // 发送广播
  sendFun(){
    var that=this;
    var udpInter;
    if (wx.canIUse('createUDPSocket')) {
      console.log('good use')
    } else {
      const version = wx.getSystemInfoSync().SDKVersion
      console.log('bad use, version is ' + version)
      wx.showToast({
        title: '不支持UDP通信',
        icon: 'none'
      })
      return;
    }
    udp = wx.createUDPSocket();
    var locationPort = udp.bind();
    console.log("当前端口 " + locationPort);
    clearInterval(that.data.apGuangBo);
    that.data.apGuangBo=setInterval(function(){
      var parms = {
        "ssid": that.data.curWifi,
        "pwd": that.data.inputNewPwdValue,
        "modelId": that.data.scanQRmodelID,
        "platform": "0"
      }
      udp.send({
        address: '255.255.255.255',
        port: 7686,
        message: JSON.stringify(parms)
      })
      console.log("send: " + JSON.stringify(parms))
    },1000)
    udp.onMessage(function (res) {
      clearInterval(that.data.apGuangBo);
      var recvMsg = util.newAb2Str(res.message);
      recvMsg = JSON.parse(recvMsg);
      if (recvMsg["errCode"]==0 && !that.data.isConnecting) {
        udp.close();
        that.setData({
          isConnecting: true
        })
        wx.connectWifi({
          SSID: that.data.curWifi,
          password: that.data.inputNewPwdValue,
          success: function (res) {
            that.setData({
              isConnecting: false
            })
            wx.showToast({
              title: "已连接至" + that.data.curWifi,
              icon: 'none',
              duration: 2000
            })
            that.sendDiscoverFun();
          },
          fail: function (err) {
            console.log(err);
            that.setData({
              isConnecting: false
            })
          }
        })
      }
      else if (recvMsg["errCode"] == 1){
        wx.showToast({
          title: '型号不匹配！',
          icon: 'none'
        })
      }
    })
  },
  // 开始配置
  startMatch:function(){
    var that=this;
    // clearInterval(clearProgress);
    that.setData({
      isMatch: !that.data.isMatch
    })
    if(that.data.isMatch){
      if (that.data.inputNewPwdValue.length == 0) {
        wx.showToast({
          title: '请输入密码',
          icon: 'none'
        })
      } else {
        clearInterval(that.data.progressInter);
        that.data.progressInter = setInterval(function () {
          if (that.data.progressVal < 100) {
            that.setData({
              progressVal: parseInt(that.data.progressVal) + 1
            })
          } else {
            that.setData({
              progressVal: 0
            })
            clearInterval(that.data.progressInter);
          }
        }, 2000);
        if (app.globalData.isAndroidPlatform) {
          // 授权获取地理位置
          let vm = this;
          wx.getSetting({
            success: (res) => {
              console.log(JSON.stringify(res));
              // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
              // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
              // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
              // 拒绝授权后再次进入重新授权
              if (res.authSetting['scope.userLocation'] == false) {
                // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
                wx.showModal({
                  title: '',
                  content: '为了更好的为您服务,【壁挂炉】需要获取你的地理位置，请确认授权',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: function (dataAu) {
                          // console.log('dataAu:success', dataAu)
                          if (dataAu.authSetting["scope.userLocation"] == true) {
                            //再次授权，调用wx.getLocation的API
                            // vm.getLocation(dataAu);
                            app.globalData.isUserLocation = true;
                          } else {
                            app.globalData.isUserLocation = false;
                          }
                        }
                      })
                    }
                  }
                })
              }// 初始化进入，未授权
              else if (res.authSetting['scope.userLocation'] == undefined) {
                // console.log('authSetting:status:初始化进入，未授权', res.authSetting['scope.userLocation'])
                //调用wx.getLocation的API
                app.globalData.isUserLocation = false;
                // vm.getLocation(res);
              }
              // 已授权
              else if (res.authSetting['scope.userLocation']) {
                // console.log('authSetting:status:已授权', res.authSetting['scope.userLocation'])
                //调用wx.getLocation的API
                app.globalData.isUserLocation = true;
                // vm.getLocation(res);

              }
            }
          })
        }
        if (app.globalData.isUserLocation){
          that.wifiListFun();
        }
      }
    }
  },
  wifiListFun: function(){
    var that=this;
    wx.getWifiList({
      success: (res) => {
        console.log("447:" + JSON.stringify(res));
        that.setData({
          apWifi: []
        })
        wx.onGetWifiList((res) => {
          console.log("453:aaa" + JSON.stringify(res.wifiList));
          const wifiList = res.wifiList;
          for (var i = 0; i < wifiList.length; i++) {
            var ssid = wifiList[i].SSID;
            if (ssid.indexOf("zcy_" + app.globalData.wifiModeId) > -1) {
              that.data.apWifi.push(wifiList[i]);
            }
          }
          if (that.data.apWifi.length) {
            if (!app.globalData.isAndroidPlatform) {
              wx.setWifiList({
                wifiList: [{
                  SSID: that.data.apWifi[0].SSID,
                  password: ''
                }]
              })
              that.sendFun();
            } else {
              wx.connectWifi({
                SSID: that.data.apWifi[0].SSID,
                password: '',
                success: function (res) {
                  console.log("已连接至" + that.data.apWifi[0].SSID);
                  that.sendFun();
                },
                fail: function (err) {
                  console.log(err);
                }
              })
            }
          } else {
            setTimeout(function () {
              wx.showToast({
                title: '请确认设备是否进入ap模式',
                icon: 'none'
              })
              that.wifiListFun();
            }, 3000)
          }
        })
      },
      fail(err) {
        console.error(err);
      }
    })
  }
})